package Server;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RemoteServer;

import General.RegistryInterface;
	
public class Server {
	
	private String fHost;
	private String fRegistryIp;
	private int fRegistryPort;
	
	public Server(String host, String registryIp, int registryPort) {
		fHost = host;
		fRegistryIp = registryIp;
		fRegistryPort = registryPort;
	}
	
	public void start() {
		
		// Set up log file
		try {
			FileOutputStream logFile = new FileOutputStream("server.log");
			RemoteServer.setLog(logFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		try {
			// Locate registry
			Registry registry = LocateRegistry.getRegistry(fRegistryIp, fRegistryPort);
			RegistryInterface registryInt;
			registryInt = (RegistryInterface)registry.lookup("RegistryService");
			
			// Bind SubServerService
			SubServerService subserverService = new SubServerService();
			registryInt.rebind("SubServerService", subserverService);
			
			// Bind MainShipQouterService
			MainShipQuoterService shipQuoter = new MainShipQuoterService(subserverService);
			registryInt.rebind("MainShipQuoteService", shipQuoter);
			
			// Bind AdminService
			AdminService admin = new AdminService(subserverService);
			registryInt.rebind("AdminService", admin);
			
			// Output
			System.out.println("[SERVER] Server started on host " + fHost); 
			
		} catch (NotBoundException e) {
			e.printStackTrace();
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
	}
}
